package org.team4.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.team4.constants.SQLConstant;
import org.team4.domain.Department;
import org.team4.exception.CRUDException;
import org.team4.util.CodeHelper;
import org.team4.vo.Page;

import org.team4.dao.DepartmentDAO;
import org.team4.dao.GenericDAO;

/**
 * <p>程序名称：       DepartmentDAO.java</p>
 * <p>程序说明：       部门DAO</p>
 * <p>版权信息：       Copyright 深圳市维远泰克科技有限公司</p>
 * <p>时间：          Jan 7, 2011 4:03:51 PM</p>	
 * 
 * @author：          Marker.King
 * @version：         Ver 0.1
 */
public class DepartmentDAO extends GenericDAO<Department> {

	private static final long serialVersionUID = 376038639038947152L;
	private static DepartmentDAO instance;
	
	public static DepartmentDAO getInstance(SessionFactory sessionFactory) {
        if(instance == null) {
            instance =  new DepartmentDAO(sessionFactory);
        }
        return instance;
    }
	
	private DepartmentDAO(SessionFactory sessionFactory) {
		super(sessionFactory, Department.class);
	}
	
	/**
	 * 查找下一个编号
	 * @param superId
	 * @return
	 * @throws CRUDException
	 */
	public String findNextCode(String superId) throws CRUDException {
		Page<Department> page = new Page<Department>();
		page.setCurrPage(1);
		page.setPageSize(1);
		page = pagination(page, SQLConstant.DEPARTMENT_CHILD_HQL, "code desc", superId);

		String nextCode = "";
		if(page.getList().size() > 0) {
			nextCode = CodeHelper.getNextCode(page.getList().get(0).getCode(), CodeHelper.DEPARTMENT_CODE_LENGTH);
		} else {
			Department d = this.get(superId);
			if(d == null) {
				nextCode = CodeHelper.getFirstCode(null, CodeHelper.DEPARTMENT_CODE_LENGTH);
			} else {
				nextCode = CodeHelper.getFirstCode(d.getCode(), CodeHelper.DEPARTMENT_CODE_LENGTH);
			}
		}
		
		return nextCode;
	}
	
	/**
	 * 获得部门权限的where语句
	 * @param idList
	 * @return
	 * @throws CRUDException
	 */
	public String findDepartmentWhere(List<String> idList) throws CRUDException {
		StringBuffer sb = new StringBuffer();
		for (Iterator iterator = idList.iterator(); iterator.hasNext();) {
			String id = (String) iterator.next();
			sb.append(" or code like '");
			sb.append(this.get(id).getCode());
			sb.append("%'");
		}
		return sb.toString();
	}

}